#!/bin/bash

############################
# CONFIGURATION
############################
INSTALL_FOLDER=/Applications
[ -n "$2" ] && INSTALL_FOLDER="$2"

APP_NAME="Once Sport.app"
DMG_PATH="/tmp/oncesport.dmg"
APP_INSTALL_PATH="$INSTALL_FOLDER/$APP_NAME"
LOG_FILE="/tmp/oncesport_installer.log"

# Start fresh log
echo "=== Once Sport Installer started at $(date) ===" | tee "$LOG_FILE"

log() {
    # Write both to stdout and log file
    echo "$(date '+%Y-%m-%d %H:%M:%S') $*" | tee -a "$LOG_FILE"
}

log "Install folder: $INSTALL_FOLDER"
log "Full install path (app bundle): $APP_INSTALL_PATH"

############################
# ARCHITECTURE CHECK
############################
if [ "$(uname -m)" = "arm64" ] || [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = "1" ]; then
    DOWNLOAD_URL="https://cdn.once.sport/v4/mac/a64/oncesport.dmg"
    log "Detected ARM64 Mac, using URL: $DOWNLOAD_URL"
else
    DOWNLOAD_URL="https://cdn.once.sport/v4/mac/x64/oncesport.dmg"
    log "Detected x86_64 Mac, using URL: $DOWNLOAD_URL"
fi

############################
# INSTALL/UPDATE PROMPT
############################
if [ "$1" != "N" ]; then
    if [ -d "$APP_INSTALL_PATH" ]; then
        BUTTON=$(osascript -e 'display dialog "Once Sport is already installed.\n\nDo you want to update it?" buttons {"Update", "Exit"} with title "Once Sport Installer"')
        [ "$BUTTON" = "button returned:Exit" ] && { log "User cancelled update."; exit 0; }
    else
        BUTTON=$(osascript -e 'display dialog "Do you want to install Once Sport?" buttons {"Install", "Exit"} with title "Once Sport Installer"')
        [ "$BUTTON" = "button returned:Exit" ] && { log "User cancelled install."; exit 0; }
    fi
fi

############################
# PERMISSIONS CHECK
############################
TOUCH_TEST="$INSTALL_FOLDER/.write_test"
if ! touch "$TOUCH_TEST" 2>/dev/null; then
    osascript -e "display dialog \"Install folder '$INSTALL_FOLDER' is not writable.\nPlease install manually.\" buttons {\"Exit\"} with title \"Once Sport Installer\""
    log "Install folder not writable: $INSTALL_FOLDER"
    exit 1
else
    rm "$TOUCH_TEST"
fi

############################
# DOWNLOAD DMG
############################
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
DOWNLOADER_BIN="$SCRIPT_DIR/downloader"

log "Starting download from $DOWNLOAD_URL"
osascript -e 'display notification "Starting app download (~200MB)." with title "Once Sport Installer"'

if [ -x "$DOWNLOADER_BIN" ]; then
    log "Using custom downloader UI."

    # Run downloader, redirecting both stdout and stderr to the log file
    "$DOWNLOADER_BIN" "$DOWNLOAD_URL" "$DMG_PATH" >> "$LOG_FILE" 2>&1
    DOWNLOAD_EXIT_CODE=$?

    if [ $DOWNLOAD_EXIT_CODE -ne 0 ]; then
        log "Downloader exited with code $DOWNLOAD_EXIT_CODE. Treating as failure/cancel."
        [ -f "$DMG_PATH" ] && rm "$DMG_PATH"
        exit 1
    fi
    log "Downloader UI closed successfully."
else
    log "Downloader binary not found, using curl."
    if ! curl -fL "$DOWNLOAD_URL" -o "$DMG_PATH" -s >> "$LOG_FILE" 2>&1; then
        log "Curl download failed."
        exit 1
    fi
fi

# Verify file integrity after download
if [ ! -f "$DMG_PATH" ] || [ $(stat -f%z "$DMG_PATH") -lt 1048576 ]; then
    log "Error: DMG file is missing or corrupted."
    [ -f "$DMG_PATH" ] && rm "$DMG_PATH"
    exit 1
fi

log "Download completed: $DMG_PATH"
osascript -e 'display notification "Download finished!" with title "Once Sport Installer"'

############################
# MOUNT DMG
############################
MOUNT_OUTPUT=$(hdiutil attach "$DMG_PATH" -nobrowse -noverify -noautoopen 2>&1)
MOUNT_POINT=$(echo "$MOUNT_OUTPUT" | awk -F'\t' '/\/Volumes/ {print $NF}' | sed 's/^.*\/Volumes/\/Volumes/')

if [ ! -d "$MOUNT_POINT" ]; then
    osascript -e "display notification \"Failed to mount $DMG_PATH\" with title \"Once Sport Installer\""
    log "Failed to mount DMG: $DMG_PATH"
    exit 1
fi
log "Mounted DMG at: $MOUNT_POINT"

############################
# REMOVE EXISTING INSTALL
############################
if [ -d "$APP_INSTALL_PATH" ]; then
    log "Removing existing installation: $APP_INSTALL_PATH"
    rm -rfv "$APP_INSTALL_PATH" >> "$LOG_FILE" 2>&1
fi

############################
# COPY APP
############################
log "Copying $MOUNT_POINT/$APP_NAME to $INSTALL_FOLDER/"
cp -Rv "$MOUNT_POINT/$APP_NAME" "$INSTALL_FOLDER/" >> "$LOG_FILE" 2>&1

############################
# DETACH DMG
############################
hdiutil detach "$MOUNT_POINT" -quiet
log "Detached DMG from $MOUNT_POINT"

osascript -e 'display notification "Installation complete!" with title "Once Sport Installer"'
log "Installation complete"

############################
# REMOVE LEGACY APP
############################
OLD_APP="/Applications/Once.VideoAnalyser.app"
if [ -d "$OLD_APP" ]; then
    log "Removing legacy app: $OLD_APP"
    rm -rf "$OLD_APP"
fi

############################
# LAUNCH PROMPT
############################
BUTTON=$(osascript -e 'display dialog "Install finished!\n\nDo you want to launch Once Sport?" buttons {"Launch", "Exit"} with title "Once Sport Installer"')
if [ "$BUTTON" = "button returned:Launch" ]; then
    log "User chose to launch app: $APP_INSTALL_PATH"
    open "$APP_INSTALL_PATH"
else
    log "User chose not to launch app"
fi

log "=== Installer finished at $(date) ==="